/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelBody from "../aftersale/aftersale.vue"
// import modelFooter from "../../inventoryinfo/goodsin_class/goodsInCom.vue"
import modelFooter from "../../inventoryinfo/goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: modelBody,
    modelFooter: modelFooter
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    async onInit() { //框架初始化配置前，
      this.queryFields = ["Client", "CreateDate"]
      let startTime = this.base.getOneWeekAgoDate()
      let endTime = this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      this.detailOptions.textInline = false
      this.textInline = false
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == 'Attachment' || item.field == 'Image') {
            item.multiple = true;
            item.maxFile = 10;
          }
        })
      })
      if (this.$route.path == "/q_serve_contract" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.Voucher_sub_aftersale = null
        // this.searchFormFields.Client = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.Signed_date = [null, null]
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Voucher_sub', 'Voucher_sub_aftersale',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    async onInited() {
      // await this.setFiexdSearchForm(true);
      // await this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      await this.detailOptions.buttons.splice(this.detailOptions.buttons.findIndex(item => item.name == "添加行"), 1)
      this.detailOptions.buttons.unshift({
        name: "选择配件", //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件
          // this.$refs.modelFooter.open(this.editFormFields.Tax_rate)
          // return;
          if (this.rowschild) {
            this.rowschild.click()
          }
          if (!this.editFormFields.Tax_rate) {
            this.base.ElMessageFn("请选择税率")
            return 
          }
          if (!this.editFormFields.WHSE_no) {
            this.base.ElMessageFn("请选择机构")
            return 
          }
          this.$refs.modelFooter.open(this.editFormFields.Tax_rate,this.editFormFields.WHSE_no)
          this.$store.commit("setTabelText", true)
        }
      })

      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_serve_contract" || this.rowAuditStatus != 0) return false; //|| !this.CreateUserBoole
        this.detailOptions.columns.forEach(item => {
          let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
          this.rowschild = rows[0].childNodes[2]
          setTimeout(() => {
            //数量
            let testInputDom = rows[index].querySelectorAll("td")[5].querySelector("input")
            testInputDom.addEventListener("keyup", (e) => {
              if (+e.target.value) {
                if (row.Goods_price) {
                  //总价
                  row.Total_price = row.Goods_price * e.target.value
                  //无税总价
                  if (this.editFormFields.Tax_rate) {
                    const num = row.Tax_exclusive_goods_price * e.target.value
                    row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)
                  }
                }
              } else {
                row.Total_price = ""
                row.Tax_exclusive_total_price = ""
                this.base.ElMessageFn("请输入有效数字")
              }
            })
            //单价
            let testInputDom2 = rows[index].querySelectorAll("td")[6].querySelector("input")
            testInputDom2.addEventListener("keyup", (e) => {
              // if (+e.target.value) {
              //   if (row.Goods_num) {
              //     //总价
              //     row.Total_price = row.Goods_num * e.target.value
              //     //无税总价
              //     if (this.editFormFields.Tax_rate) {
              //       const num = row.Total_price / (1 + +this.editFormFields.Tax_rate)
              //       row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)
              //     }
              //   }
              //   //无税单价
              //   if (this.editFormFields.Tax_rate) {
              //     const num = e.target.value / (1 + +this.editFormFields.Tax_rate)
              //     row.Tax_exclusive_goods_price = this.base.roundToFourDecimals(num)

              //   }
              // } else {
              //   row.Total_price=""
              //   row.Tax_exclusive_goods_price=""
              //   row.Tax_exclusive_total_price=""
              //   this.base.ElMessageFn("请输入有效数字")
              // }
              if (!+e.target.value && +e.target.value !== 0) {
                row.Total_price = ""
                row.Tax_exclusive_goods_price = ""
                row.Tax_exclusive_total_price = ""
                this.base.ElMessageFn("单价请输入有效数字")
                return
              }
              if (e.target.value < 0) {
                row.Total_price = ""
                row.Tax_exclusive_goods_price = ""
                row.Tax_exclusive_total_price = ""
                this.base.ElMessageFn("单价请请输入正数")
                return
              }
              //无税单价
              if (this.editFormFields.Tax_rate) {
                const num = e.target.value / (1 + +this.editFormFields.Tax_rate)
                row.Tax_exclusive_goods_price = this.base.roundToFourDecimals(num)
              }
              if (!+row.Goods_num && row.Goods_num != undefined) {
                row.Total_price = ""
                row.Tax_exclusive_total_price = ""
                this.base.ElMessageFn("数量请输入有效数字")
                return
              }
              if (+e.target.value || +e.target.value >= 0) {
                if (row.Goods_num) {
                  row.Total_price = this.base.roundToFourDecimals(row.Goods_num * e.target.value)
                }
                //无税总价
                if (this.editFormFields.Tax_rate && row.Goods_num) {
                  let num = row.Tax_exclusive_goods_price * row.Goods_num
                  row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)
                }
              } else {
                this.base.ElMessageFn("请输入数字")
              }
            })
          })
        })
        return true
      }
    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_serve_contract" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Serve_contract", param)
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // const dateState2 = sectionState.includes(JSON.stringify(this.searchFormFields.Signed_date))
        // if (this.searchFormFields.Voucher_sub || this.searchFormFields.Voucher_sub_aftersale || !dateState || !dateState2) {
        //   param.wheres = param.wheres.filter(item => item.name != "Serve_contract")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    addBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    async updateBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    detailRowClick({
      row,
      column,
      event
    }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_serve_contract" || this.rowAuditStatus != 0) {
        return
      }; //|| !this.CreateUserBoole
      if (column.property == "Goods_num" || column.property == "Goods_price" || column.property == "Remark") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }

      }
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_serve_contract" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }

    },
    modelOpenAfter(row) {
      console.log(this.currentAction);
      if (this.currentAction == "Add") {
        this.editFormFields.Service_charge = 0
        this.editFormFields.Signed_date = this.base.getDate()
      }
      this.rowschild = null
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "Aftersale_ID") {
            x.hidden = true
          }
          if (x.field == "Tax_rate") {
            x.onChange = (e) => {
              let detailDate = this.$refs.detail.rowData
              detailDate.forEach(d => {
                if (+d.Goods_price) {
                  const num = d.Goods_price / (1 + +e)
                  d.Tax_exclusive_goods_price = this.base.roundToFourDecimals(num)
                  if (d.Goods_num) {
                    const num = (d.Goods_price * d.Goods_num) / (1 + +e)
                    d.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)
                  }
                } else {
                  d.Tax_exclusive_goods_price = ""
                  d.Tax_exclusive_total_price = ""
                }

              })
            }
          }
          x.disabled = false
          if (x.field == "Voucher_sub" || x.field == "Goods_num" || x.field == "Client" || x.field == "Voucher_sub_aftersale" || x.field == "Contract_total_prices" || x.field == "Tax_exclusive_contract_total_prices") {
            x.disabled = true
          }
          if (x.field == "Goods_num" || x.field == "Contract_total_prices" || x.field == "Tax_exclusive_contract_total_prices") {
            x.hidden = true
          }
          if (x.field == "Voucher_sub_aftersale") {
            x.extra = {
              icon: "el-icon-zoom-in",
              text: "售后服务单",
              style: "color:#3a8ee6;font-size:13px;cursor:pointer;",
              click: () => {
                this.$refs.modelBody.open()
                this.$store.commit("setTabelText", true)
              }
            }
          }
          if (this.currentAction != 'Add' && (x.field == "WHSE_no"||x.field == "Tax_rate")) {
            x.disabled = true
          }
          if (this.$route.path != "/q_serve_contract" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
            if (x.field == "Voucher_sub_aftersale") {
              x.extra = null
            }
          }
        })
      })

    },
    testAdd(formData) {
      if (this.currentAction == "Add") {
        formData.mainData.Goods_num = 0
        formData.mainData.Contract_total_prices =
          formData.mainData.Tax_exclusive_contract_total_prices = 0
      }
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn('请选择机构')
        return false
      }
      // let boole = formData.detailData.some(item => item.Goods_num <= 0 || item.Goods_num == null)
      // let boole = formData.detailData.every(item => item.Goods_num > 0 && +item.Goods_num)
      // let chenben1 = formData.detailData.every(item => item.Goods_price > 0 && +item.Goods_price)
      // let chenben2 = formData.detailData.every(item => +item.Goods_price == true || item.Goods_price > 0)
      // if (!boole) {
      //   this.base.ElMessageFn("明细表中数量请大于零")
      //   return false;
      // }
      // if (!chenben2) {
      //   this.base.ElMessageFn("明细表中单价请填写有效数字")
      //   return false;
      // }
      // if (!chenben1) {
      //   this.base.ElMessageFn("明细表中单价请大于零")
      //   return false;
      // }
      let boole = formData.detailData.some(item => item.Goods_num === "" || item.Goods_num === null || item.Goods_num === undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写数量")
        return false;
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0 && (item.Goods_num != "" || item.Goods_num != null || item.Goods_num == undefined))
      if (boole2) {
        this.base.ElMessageFn("明细表中数量不可为零")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中数量请填写有效正数")
        return false;
      }

      // let boole1 = formData.detailData.some(item => item.Goods_price === "" || item.Goods_price === null || item.Goods_price === undefined)
      // if (boole1) {
      //   this.base.ElMessageFn("明细表中请填写单价")
      //   return false;
      // }
      // let boole22 = formData.detailData.some(item => +item.Goods_price === 0 &&(item.Goods_price!=""||item.Goods_price!=null|| item.Goods_price == undefined))
      // if (boole22) {
      //   this.base.ElMessageFn("明细表中单价不可为零")
      //   return false;
      // }
      //   let boole33 = formData.detailData.every(item => +item.Goods_price > 0 && +item.Goods_price)
      //   if (!boole33) {
      //     this.base.ElMessageFn("明细表中单价请填写有效正数")
      //     return false;
      //   }
      let boole1 = formData.detailData.some(item => item.Goods_price === "" || item.Goods_price === null || item.Goods_price === undefined)
      if (boole1) {
        this.base.ElMessageFn("明细表中请填写单价")
        return false;
      }
      let boole22 = formData.detailData.every(item => item.Goods_price !== "" || item.Goods_price !== null || item.Goods_price === undefined || item.Goods_price ? ("" + item.Goods_price).trim() !== "" : +item.Goods_price)
      if (!boole22) {
        this.base.ElMessageFn("明细表中单价不可为空")
        return false;
      }
      let boole33 = formData.detailData.every(item => +item.Goods_price >= 0)
      if (!boole33) {
        this.base.ElMessageFn("明细表中单价请填写有效正数")
        return false;
      }
      return true
    },
  }
};
export default extension;